<?php
namespace app\appapi\controller;
use think\Controller;
use think\Request;
use think\Db;
use app\appapi\WeShare;
use app\appapi\WXBizDataCrypt;

class WeBusinesscard extends Common

{
    //更新添加个人名片
    public function getAddUserCardInfo()
    {
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        $time = time();
        $arr['Realname'] = $data['Realname'];
        $arr['Phone'] = $data['Phone'];
        $arr['Wechat'] = $data['Wechat'];
        if(!empty($data['Company']))
        $arr['Company'] = $data['Company'];
        if(!empty($data['Occupation']))
        $arr['Occupation'] = $data['Occupation'];
        if(!empty($data['Card_portrait']))
        $arr['Card_portrait'] = $data['Card_portrait'];
        if(!empty($data['Card_address']))
        $arr['Card_address'] = $data['Card_address'];
        if($re = $this->_judgeUserCardInfo($uid)){
            // if($time - $re['Addtime']<30*24*3600)
            // return json_encode(['code'=>10002,'msg'=>'名片30天内仅能修改一次']);
			$where['User_id'] = ['=',$uid];
			Db::startTrans();
			try{
				if(Db::name('user_card')->where($where)->update($arr)){
					//确认更新成功再更新时间
					Db::name('user_card')->where($where)->setField('Addtime',$time);
					Db::commit();
					return json_encode(['code'=>10001,'msg'=>'更新成功','data'=>$arr]);
				}
				return json_encode(['code'=>10002,'msg'=>'更新失败']);
			}catch(\Exception $e){
				Db::rollback();
				return json_encode(['code'=>10002,'msg'=>'更新失败']);
			}
        }else{
			$arr['Addtime'] = $time;
            $arr['User_id'] = $uid;
            if(Db::name('user_card')->insert($arr))
            return json_encode(['code'=>10001,'msg'=>'更新成功','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'更新失败']);
    }

    //统一更新单个名片信息（除海报外）
    public function getUpdateUserCardInfo()
    {
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'] || empty($data['field']) || !$data['field'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        $field = $data['field'];
        unset($data['field']);
        $where['User_id'] = ['=',$uid];
        if(!$re = $this->_judgeUserCardInfo($uid)){//没有就添加
            //或者返回提示信息
            return json_encode(['code'=>10002,'msg'=>'请先完善名片信息']);
        }else{
            $re = Db::name('user_card')->where($where)->field($field)->update($data);
        }
        if($re)
        return json_encode(['code'=>10001,'msg'=>'更新成功','data'=>$data]);
        return json_encode(['code'=>10002,'msg'=>'更新失败']);
    }

    //更新添加缘分基因
    public function getAddUserFateGene()
    {
        $data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        unset($data['uid']);
        $time = time();
        $arr['Hometowns'] = $data['Hometowns'];
        $arr['Locations'] = $data['Locations'];
        $arr['Campus'] = $data['Campus'];
        $arr['Industrys'] = $data['Industrys'];
        $arr['Hobbys'] = $data['Hobbys'];
        $arr['Age'] = $data['Age'];
        $arr['Demand'] = $data['Demand'];
        $arr['Languages'] = $data['Languages'];
        $arr['Gender'] = $data['Gender'];
        $arr['Marriage'] = $data['Marriage'];
        $arr['Position'] = $data['Position'];
        $arr['Longitud'] = $data['Longitud'];
        $arr['Latitude'] = $data['Latitude'];
        if($re = $this->_judgeUserFateGene($uid)){
            if($time - $re['Addtime']<30*24*3600)
            return json_encode(['code'=>10002,'msg'=>'缘分基因30天内仅能修改一次']);
			$where['User_id'] = ['=',$uid];
			Db::startTrans();
			try{
				if(Db::name('user_fate_gene')->where($where)->update($arr)){
					//确认更新成功再更新时间
					Db::name('user_fate_gene')->where($where)->setField('Addtime',$time);
					Db::commit();
					return json_encode(['code'=>10001,'msg'=>'更新成功','data'=>$arr]);
				}
				return json_encode(['code'=>10002,'msg'=>'更新失败']);
			}catch(\Exception $e){
				Db::rollback();
				return json_encode(['code'=>10002,'msg'=>'更新失败']);
			}
        }else{
			$arr['Addtime'] = $time;
            $arr['User_id'] = $uid;
            if(Db::name('user_fate_gene')->insert($arr))
            return json_encode(['code'=>10001,'msg'=>'更新成功','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'更新失败']);
    }


    //上传图片
    public function getUploadFileLocal()
    {
        $file = request()->file('file');
        $data = $_REQUEST;
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        if($file) {
            //$paths = 'public/upload/wxHead/';//本地解开
            $paths = '../public/upload/wxHead/';
            $info = $file->move($paths);    
            $db = Db::name('user_poster');                
            if ($info) {
                $filename = $info->getSaveName();
                $filename = str_replace('\\', '/', $filename);
                //$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/public/upload/wxHead/'.$filename;//本地解开
                $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/upload/wxHead/'.$filename;                                                                  
                header('content-type:application/json;charset=utf-8');
                return json_encode(['code'=>10001,'msg'=>'上传成功','data'=>$url]);             
            }
            return json_encode(['code'=>10002,'msg'=>'上传失败']);
        }
       
    }

    //上传海报(到本地服务器)
    public function getUploadPosterLoading()
    {
        $file = request()->file('file');
        $data = $_REQUEST;
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $id = !empty($data['id'])?$data['id']:0;
        $where['User_id'] = ['=',$uid];
        $where['id'] = ['=',$id];
        $poster = array();
        if($file) {
            //$paths = 'public/upload/weixin/';//本地解开    
            $db = Db::name('user_poster');   
            $count = $db->where(array('User_id'=>$uid))->count();
            if($count>10)
            return json_encode(['code'=>10002,'msg'=>'上传失败，超过数量限制']);   
            $paths = '../public/upload/weixin/';
            $info = $file->move($paths);          
            if ($info) {
                $filename = $info->getSaveName();
                $filename = str_replace('\\', '/', $filename);
                //$url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/public/upload/weixin/'.$filename;//本地解开
                $url = 'http://'.$_SERVER['HTTP_HOST'].dirname($_SERVER['SCRIPT_NAME']).'/upload/weixin/'.$filename;
				$time = time();
                if(!$re = $db->where($where)->find()){
                    $arr = [
                        'User_id' => $uid,
                        'Url' => $url,
						'Addtime' => $time,
                    ];
                    $re = $db->insertGetId($arr);
                }else{
                    $file = $db->where($where)->value('Url');
					$arr = [
                        'Url' => $url,
						// 'Addtime' => $time,
                    ];
                    if($re = $db->where($where)->update($arr)){
                        deleFile($file);//删除本地文件
                    }
                }                                                                  
                header('content-type:application/json;charset=utf-8');
                if($re){
					$poster = getUserPosterInfo($uid);
                    return json_encode(['code'=>10001,'msg'=>'上传成功','data'=>$poster]);
                }
                
            }
        }
        return json_encode(['code'=>10002,'msg'=>'上传失败']);
       
    }

	//更新海报(数据库)
	public function getUpdateUserPoster()
	{
		$data = input('post.');
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        if(empty($data['uid']) || !$data['uid'] || empty($data['poster']) || !$data['poster'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
		$url = $data['poster'];
		$id = !empty($data['id'])?$data['id']:0;
        $where['User_id'] = ['=',$uid];
		$db = Db::name('user_poster');   
        $count = $db->where($where)->count();
        if($count>10)
        return json_encode(['code'=>10002,'msg'=>'上传失败，超过数量限制']);   
        $where['id'] = ['=',$id];
		$time = time();
		if(!$re = $db->where($where)->find()){
            $arr = [
                'User_id' => $uid,
                'Url' => $url,
				'Addtime' => $time,
                ];
            $re = $db->insertGetId($arr);
		}else{
			$file = $db->where($where)->value('Url');
			$arr = [
                'Url' => $url,
				// 'Addtime' => $time,
                ];
            if($re = $db->where($where)->update($arr)){
            	$this->deleteOssFile($file);//删除oss文件
            }
		}
		if($re){
			$poster = getUserPosterInfo($uid);
            return json_encode(['code'=>10001,'msg'=>'上传成功','data'=>$poster]);
        }
		return json_encode(['code'=>10002,'msg'=>'上传失败']);
	}

    //删除海报
    public function getDellUserPost()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['id']) || !$data['id'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $id = $data['id'];
        $where['User_id'] = ['=',$uid];
        $where['id'] = ['=',$id];
        $db = Db::name('user_poster');    
        if(!$file = $db->where($where)->value('Url'))
        return json_encode(['code'=>10002,'msg'=>'删除失败']);
        if($db->where($where)->delete()){
            //deleFile($file);//删除本地文件
			$this->deleteOssFile($file);//删除oss文件
            $poster = getUserPosterInfo($uid);
            return json_encode(['code'=>10001,'msg'=>'删除成功','data'=>$poster]);
        }
        return json_encode(['code'=>10002,'msg'=>'删除失败']);
    }
    //检测用户名片信息
    private function _judgeUserCardInfo($uid)
    {
        $where['User_id'] = ['=',$uid];
        if($re = Db::name('user_card')->where($where)->find())
        return $re;
        return false;
    }
    //检测用户缘分基因
    private function _judgeUserFateGene($uid)
    {
        $where['User_id'] = ['=',$uid];
        if($re = Db::name('user_fate_gene')->where($where)->find())
        return $re;
        return false;
    }
    //获取用户绑定微信手机号
    public function getUserWxBindingPhone()
    {
        if(!$uid = $this->WxApp_User_Id)
        return json_encode(['code'=>10003,'msg'=>'登陆超时']);
        $data = input('post.');
        if(empty($data['uid']) || !$data['uid'] || empty($data['iv']) || !$data['iv'] || empty($data['encryptedData']) || !$data['encryptedData'])
        return json_encode(['code'=>10002,'msg'=>'参数错误']);
        $uid = $data['uid'];
        $iv = $data['iv'];
        $encryptedData = $data['encryptedData'];
        $weapp = new WeShare(); 
        $wAppconfig = getWxconfig('weAppSystem');//微信小程序配置
        $appid = $wAppconfig['app_id'];
		if(!empty($data['ss_key']) && $data['ss_key'] && $data['ss_key'] !=''){
			$sessionKey = $data['ss_key'];
		}else{
			if(empty($data['code']) || !$data['code'] )
			return json_encode(['code'=>10002,'msg'=>'code参数错误']);
			$code = $data['code'];
			$secret = $wAppconfig['secret'];
			$grant_type='authorization_code';
			$url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=$grant_type";
			$result = $weapp->getDataCurl($url);
			if(!$result || empty($result['session_key']))
			return json_encode(['code'=>10002,'msg'=>'网络异常','data'=>$data]);
			$sessionKey = $result['session_key'];
		}
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $arr = $pc->decryptData($encryptedData, $iv);
        if($arr){
            unset($arr['watermark']);
            return json_encode(['code'=>10001,'msg'=>'解密成功','data'=>$arr]);
        }
        return json_encode(['code'=>10002,'msg'=>'网络繁忙']);
    }
}
